package com.yuanqi.service.impl;

import com.yuanqi.domain.PaymentApproval;
import com.yuanqi.repository.PaymentApprovalRepository;
import com.yuanqi.service.PaymentApprovalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class PaymentApprovalServiceImpl implements PaymentApprovalService {
    
    @Autowired
    private PaymentApprovalRepository paymentApprovalRepository;
    
    @Override
    public Page<PaymentApproval> getPaymentApprovals(String applicant, String status, String applyDate, Pageable pageable) {
        List<PaymentApproval> allApprovals = new ArrayList<>();
        
        if (applicant != null && !applicant.trim().isEmpty() && status != null && !status.trim().isEmpty()) {
            Integer statusInt = Integer.parseInt(status);
            allApprovals = paymentApprovalRepository.findByApplicantAndStatus(applicant, statusInt);
        } else if (applicant != null && !applicant.trim().isEmpty()) {
            allApprovals = paymentApprovalRepository.findByApplicant(applicant);
        } else if (status != null && !status.trim().isEmpty()) {
            Integer statusInt = Integer.parseInt(status);
            allApprovals = paymentApprovalRepository.findByStatus(statusInt);
        } else {
            allApprovals = paymentApprovalRepository.findAll();
        }
        
        // 实现简单的分页逻辑
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), allApprovals.size());
        
        if (start > allApprovals.size()) {
            return new org.springframework.data.domain.PageImpl<>(new ArrayList<>(), pageable, allApprovals.size());
        }
        
        List<PaymentApproval> pageContent = allApprovals.subList(start, end);
        return new org.springframework.data.domain.PageImpl<>(pageContent, pageable, allApprovals.size());
    }
    
    @Override
    public PaymentApproval getPaymentApprovalById(Long id) {
        return paymentApprovalRepository.findById(id).orElse(null);
    }
    
    @Override
    @Transactional
    public PaymentApproval createPaymentApproval(Map<String, Object> approvalData) {
        try {
            // 数据验证
            if (approvalData.get("applicationAmount") == null) {
                throw new IllegalArgumentException("申请付款金额不能为空");
            }
            
            // 生成审批编号
            String approvalCode = generateApprovalCode();
            
            // 创建付款审批对象
            PaymentApproval approval = new PaymentApproval();
            approval.setApprovalCode(approvalCode);
            approval.setApprovalType((String) approvalData.get("approvalType"));
            approval.setOrderId(approvalData.get("orderId") != null ? Long.valueOf(approvalData.get("orderId").toString()) : null);
            approval.setOrderCode((String) approvalData.get("orderCode"));
            approval.setOrderType((String) approvalData.get("orderType"));
            approval.setSupplierId(approvalData.get("supplierId") != null ? Long.valueOf(approvalData.get("supplierId").toString()) : null);
            approval.setSupplierName((String) approvalData.get("supplierName"));
            approval.setCustomerId(approvalData.get("customerId") != null ? Long.valueOf(approvalData.get("customerId").toString()) : null);
            approval.setCustomerName((String) approvalData.get("customerName"));
            approval.setTotalAmount(approvalData.get("totalAmount") != null ? new BigDecimal(approvalData.get("totalAmount").toString()) : null);
            approval.setPendingAmount(approvalData.get("pendingAmount") != null ? new BigDecimal(approvalData.get("pendingAmount").toString()) : null);
            approval.setApplicationAmount(new BigDecimal(approvalData.get("applicationAmount").toString()));
            approval.setPaymentMethod((String) approvalData.get("paymentMethod"));
            approval.setApplicationDate(LocalDate.parse(approvalData.get("applicationDate").toString()));
            
            if (approvalData.get("dueDate") != null) {
                approval.setDueDate(LocalDate.parse(approvalData.get("dueDate").toString()));
            }
            
            approval.setRemark((String) approvalData.get("remark"));
            approval.setStatus(0); // 0-待审批
            approval.setApplicant((String) approvalData.get("applicant"));
            approval.setApplicantTime(LocalDateTime.now());
            approval.setCreateTime(LocalDateTime.now());
            approval.setUpdateTime(LocalDateTime.now());
            
            // 保存到数据库
            return paymentApprovalRepository.save(approval);
            
        } catch (Exception e) {
            throw new RuntimeException("创建付款审批失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    @Transactional
    public List<PaymentApproval> createBatchPaymentApprovals(List<Map<String, Object>> approvalDataList) {
        List<PaymentApproval> approvals = new ArrayList<>();
        
        for (Map<String, Object> approvalData : approvalDataList) {
            PaymentApproval approval = createPaymentApproval(approvalData);
            approvals.add(approval);
        }
        
        return approvals;
    }
    
    @Override
    @Transactional
    public PaymentApproval updatePaymentApproval(Long id, Map<String, Object> approvalData) {
        PaymentApproval existingApproval = paymentApprovalRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("付款审批记录不存在"));
        
        // 更新字段
        if (approvalData.get("orderType") != null) {
            existingApproval.setOrderType((String) approvalData.get("orderType"));
        }
        if (approvalData.get("orderCode") != null) {
            existingApproval.setOrderCode((String) approvalData.get("orderCode"));
        }
        if (approvalData.get("supplierName") != null) {
            existingApproval.setSupplierName((String) approvalData.get("supplierName"));
        }
        if (approvalData.get("customerName") != null) {
            existingApproval.setCustomerName((String) approvalData.get("customerName"));
        }
        if (approvalData.get("applicationAmount") != null) {
            existingApproval.setApplicationAmount(new BigDecimal(approvalData.get("applicationAmount").toString()));
        }
        if (approvalData.get("paymentMethod") != null) {
            existingApproval.setPaymentMethod((String) approvalData.get("paymentMethod"));
        }
        if (approvalData.get("dueDate") != null) {
            existingApproval.setDueDate(LocalDate.parse(approvalData.get("dueDate").toString()));
        }
        if (approvalData.get("remark") != null) {
            existingApproval.setRemark((String) approvalData.get("remark"));
        }
        
        existingApproval.setUpdateTime(LocalDateTime.now());
        
        return paymentApprovalRepository.save(existingApproval);
    }
    
    @Override
    @Transactional
    public PaymentApproval approvePayment(Long id, String approver, String approvalRemark) {
        PaymentApproval approval = paymentApprovalRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("付款审批记录不存在"));
        
        approval.setStatus(1); // 1-已通过
        approval.setApprover(approver);
        approval.setApprovalTime(LocalDateTime.now());
        approval.setApprovalRemark(approvalRemark);
        approval.setUpdateTime(LocalDateTime.now());
        
        return paymentApprovalRepository.save(approval);
    }
    
    @Override
    @Transactional
    public PaymentApproval rejectPayment(Long id, String approver, String approvalRemark) {
        PaymentApproval approval = paymentApprovalRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("付款审批记录不存在"));
        
        approval.setStatus(2); // 2-已拒绝
        approval.setApprover(approver);
        approval.setApprovalTime(LocalDateTime.now());
        approval.setApprovalRemark(approvalRemark);
        approval.setUpdateTime(LocalDateTime.now());
        
        return paymentApprovalRepository.save(approval);
    }
    
    @Override
    @Transactional
    public void deletePaymentApproval(Long id) {
        if (!paymentApprovalRepository.existsById(id)) {
            throw new RuntimeException("付款审批记录不存在");
        }
        paymentApprovalRepository.deleteById(id);
    }
    
    @Override
    public String generateApprovalCode() {
        Integer maxNumber = paymentApprovalRepository.findMaxApprovalCodeNumber();
        int nextNumber = (maxNumber != null ? maxNumber : 0) + 1;
        return String.format("PA%08d", nextNumber);
    }
    
    @Override
    public Map<String, Object> getApprovalStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 统计各状态数量
        long pendingCount = paymentApprovalRepository.countByStatus(0);
        long approvedCount = paymentApprovalRepository.countByStatus(1);
        long rejectedCount = paymentApprovalRepository.countByStatus(2);
        
        stats.put("pendingCount", pendingCount);
        stats.put("approvedCount", approvedCount);
        stats.put("rejectedCount", rejectedCount);
        
        return stats;
    }
}
